﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using Business.BookManagement.Dto;
using Business.Models;
using Business.ProductCuringManagement.Dto;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using XCZ;
using Yitter.IdGenerator;

namespace Business.ProductCuringManagement
{
    public class ProductCuringAppService : BusinessWorkFlowAppService, IProductCuringAppService
    {
        private IRepository<ProductCuring, Guid> _repository;
        private IRepository<ProductDetails, Guid> _repository1;
        public ProductCuringAppService(IRepository<ProductCuring, Guid> repository, IRepository<ProductDetails, Guid> repository1)
        {
            _repository = repository;
            _repository1 = repository1;
        }

        /// <summary>
        /// 创建或更新产品养护
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ProductCuringDto> CreateOrUpdate(ProductCuringDto input)
        {
            ProductCuring result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                input.DocumentId = YitIdHelper.NextId().ToString();
                ProductCuring entity = new ProductCuring()
                {
                    DocumentName = input.DocumentName,
                    DocumentId = input.DocumentId,
                    MaintenanceDate = input.MaintenanceDate,
                    DocumentMaker = input.DocumentMaker,
                    Warehouse = input.Warehouse,
                    CorrespondingProduct = input.CorrespondingProduct,
                    MaintenanceDesc = input.MaintenanceDesc,
                };

                foreach (var item in input.createOrUpdateCuringDto)
                {
                    ProductDetails details = new ProductDetails()
                    {
                        CuringId = input.Id,
                        ProductDetailsId = item.ProductDetailsId,
                        ProductName = item.ProductName,
                        ProductNumber = item.ProductNumber,
                        SKU = item.SKU,
                        Unit = item.Unit,
                        Number = item.Number,
                        BatchNum = item.BatchNum,
                        CreateDate = item.CreateDate,
                        ValidDate = item.ValidDate,
                        Conservators = item.Conservators,
                        Curingcycle = item.Curingcycle,
                        QualityStatus = item.QualityStatus,
                        ProcessResults = item.ProcessResults,
                        Desc = item.Desc,
                    };
                    await _repository1.InsertAsync(details);
                }
                result = await _repository.InsertAsync(ObjectMapper.Map<ProductCuringDto, ProductCuring>(input));
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }

            return ObjectMapper.Map<ProductCuring, ProductCuringDto>(result);
        }

        /// <summary>
        /// 获取产品养护列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ProductCuringDto>> GetProductCuringList(ProductCuringInputDto input)
        {
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.DocumentName.Contains(input.Filter));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                        .ToListAsync();

            var dtos = ObjectMapper.Map<List<ProductCuring>, List<ProductCuringDto>>(items);
            return new PagedResultDto<ProductCuringDto>(totalCount, dtos);
        }

        /// <summary>
        /// 删除产品养护
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task DeleteProductCuring(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }

        /// <summary>
        /// 获取产品养护详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ProductCuringDto> GetProductCuringForEdit(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<ProductCuring, ProductCuringDto>(data);
            return dto;
        }

        //public Task<ProductCuringDto> CreateOrUpdate(CreateOrUpdateCuringDto input)
        //{
        //    throw new NotImplementedException();
        //}
    }
}
